package com.hanhai.material.device.controller;

import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.device.entity.SysBadRecord;
import com.hanhai.material.device.entity.SysBadRecord1;
import com.hanhai.material.device.entity.SysProductRecord;
import com.hanhai.material.device.entity.SysProductRecordShift;
import com.hanhai.material.device.model.BadRecordModel;
import com.hanhai.material.device.service.SysBadRecord1Service;
import com.hanhai.material.device.service.SysBadRecordService;
import com.hanhai.material.device.service.SysProductRecordService;
import com.hanhai.material.device.service.SysProductRecordShiftService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

import static com.hanhai.material.device.entity.table.SysBadRecordTableDef.SYS_BAD_RECORD;
import static com.hanhai.material.device.entity.table.SysProductRecordShiftTableDef.SYS_PRODUCT_RECORD_SHIFT;
import static com.hanhai.material.utils.TimeUtils.fromDateToString;
import static com.mybatisflex.core.query.QueryMethods.distinct;
import static com.mybatisflex.core.query.QueryMethods.sum;

/**
 * 控制层。
 *
 * @author youchuang
 * @since 2023/10/18 11:26:03
 */
@RestController
@RequestMapping("/sysBadRecord")
@Log4j2
public class SysBadRecordController {

    @Autowired
    private SysBadRecordService sysBadRecordService;

    @Autowired
    private SysProductRecordService sysProductRecordService;
    @Autowired
    private SysProductRecordShiftService sysProductRecordShiftService;

    @Autowired
    private SysBadRecord1Service sysBadRecord1Service;
    /**
     * 添加。
     *
     * @param sysBadRecord
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("/save")
    public Result save(@RequestBody SysBadRecord sysBadRecord) {
        System.out.println("Sys:" + sysBadRecord);
        String id = fromDateToString("yyyyMMdd", sysBadRecord.getProductDate()) + sysBadRecord.getWorkPlanId() + sysBadRecord.getReasonTypeId() + sysBadRecord.getReasonId() + sysBadRecord.getCreateUserId()+sysBadRecord.getShift();
//        SysBadRecord badRecord = this.sysBadRecordService.getById(id);
        sysBadRecord.setId(UUID.randomUUID().toString());
        boolean result = this.sysBadRecordService.save(sysBadRecord);
//        if (badRecord == null && sysBadRecord.getNum() < 0) {
//            return ResultTool.fail("不良原因：" + sysBadRecord.getReasonName() + "没有需要修正的数据！");
//        } else if (badRecord != null) {
//            int num = badRecord.getNum() + sysBadRecord.getNum();
//            sysBadRecord.setNum(num);
//            if (num == 0) {
//                result = this.sysBadRecordService.removeById(id);
//            } else if (num < 0) {
//                return ResultTool.fail("不良原因：" + sysBadRecord.getReasonName() + "修正数量超过已存在条数，当前存在条数为：" + badRecord.getNum() + "条！");
//            } else {
//                sysBadRecord.setId(id);
//                result = this.sysBadRecordService.updateById(sysBadRecord);
//            }
//        } else {
//            QueryWrapper queryWrapper = QueryWrapper.create();
//            queryWrapper.where(SYS_PRODUCT_RECORD.WORK_PLAN_ID.eq(sysBadRecord.getWorkPlanId()));
//            queryWrapper.where(SYS_PRODUCT_RECORD.IS_NORMAL.eq(true));
//            queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_START_TIME.isNotNull(true));
//            queryWrapper.where(SYS_PRODUCT_RECORD.ACTUAL_END_TIME.isNull(true));
//            queryWrapper.where(SYS_PRODUCT_RECORD.IS_START.eq(true));
//            SysProductRecord sysProductRecord = this.sysProductRecordService.getOne(queryWrapper);
//            if (sysProductRecord != null) {
//                sysBadRecord.setProductRecordId(sysProductRecord.getId());
//            }
//            sysBadRecord.setId(id);
////            QueryWrapper qu
//            result = this.sysBadRecordService.save(sysBadRecord);
//        }
        return result ? ResultTool.success() : ResultTool.fail();
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    public boolean remove(@PathVariable Serializable id) {
        return sysBadRecordService.removeById(id);
    }

    /**
     * 根据主键更新。
     *
     * @param sysBadRecord
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("update")
    public boolean update(@RequestBody SysBadRecord sysBadRecord) {
        return sysBadRecordService.updateById(sysBadRecord);
    }

    /**
     * 查询所有。
     *
     * @return 所有数据
     */
    @PostMapping("/list")
    public Result<?> list(@RequestBody SysProductRecord sysProductRecord) {
        if(sysProductRecord.getActualStartTime()==null){
            return ResultTool.fail();
        }
        Date startDate=sysProductRecord.getActualStartTime();
        Date endDate=sysProductRecord.getActualEndTime();
        if(endDate==null){
            endDate=new Date();
        }
        String start=fromDateToString("yyyy-MM-dd HH:mm:ss",startDate);
        String end=fromDateToString("yyyy-MM-dd HH:mm:ss",endDate);
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.where(SYS_BAD_RECORD.PRODUCT_RECORD_ID.eq(sysProductRecord.getId()));
        List<SysBadRecord> sysBadRecordList=this.sysBadRecordService.list(queryWrapper);
        return sysBadRecordList.isEmpty()?ResultTool.fail():ResultTool.success(sysBadRecordList);
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    public SysBadRecord getInfo(@PathVariable Serializable id) {
        return sysBadRecordService.getById(id);
    }

    /**
     * 分页查询。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public Page<SysBadRecord> page(Page<SysBadRecord> page) {
        return sysBadRecordService.page(page);
    }


    @PostMapping("/listByCondition")
    public Result<?> listByCondition(@RequestBody SysBadRecord sysBadRecord) {
        log.error("SysBadRecord:{}", sysBadRecord);
        String productDate = fromDateToString("yyyy-MM-dd", sysBadRecord.getProductDate());
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
        queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
        queryWrapper.select(distinct(SYS_BAD_RECORD.WORK_SHOP));
        queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(productDate));
        queryWrapper.orderBy(SYS_BAD_RECORD.WORK_SHOP, true);
        System.out.println("SQL:" + queryWrapper.toSQL());
        List<SysBadRecord> sysBadRecordList = this.sysBadRecordService.list(queryWrapper);
        for (SysBadRecord badRecord : sysBadRecordList) {
            queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
            queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP.eq(badRecord.getWorkShop()));
            queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(productDate));
            queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
            queryWrapper.select(distinct(SYS_BAD_RECORD.MACHINE_NAME), SYS_BAD_RECORD.PRODUCT_NAME, SYS_BAD_RECORD.MACHINE_NAME, SYS_BAD_RECORD.PRODUCT_ID, SYS_BAD_RECORD.SHORT_NAME,SYS_BAD_RECORD.SHIFT,SYS_BAD_RECORD.WORK_SHOP,SYS_BAD_RECORD.WORK_SHOP_NAME,sum(SYS_BAD_RECORD.NUM).as("num"));
            queryWrapper.groupBy(SYS_BAD_RECORD.MACHINE_NAME);
            queryWrapper.orderBy(SYS_BAD_RECORD.MACHINE_NAME, true);

//            System.out.println("SQL:"+queryWrapper.toSQL());
            List<SysBadRecord> badRecordList = this.sysBadRecordService.list(queryWrapper);
            for (SysBadRecord record : badRecordList) {
                queryWrapper = QueryWrapper.create();
                queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
                queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP.eq(badRecord.getWorkShop()));
                queryWrapper.where(SYS_BAD_RECORD.WORK_PLAN_ID.eq(record.getWorkPlanId()));
                queryWrapper.where(SYS_BAD_RECORD.MACHINE_NAME.eq(record.getMachineName()));
                queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(productDate));
                queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
                queryWrapper.select(distinct(SYS_BAD_RECORD.WORK_PLAN_ID), SYS_BAD_RECORD.PRODUCT_ID, SYS_BAD_RECORD.PRODUCT_NAME, SYS_BAD_RECORD.SHORT_NAME, SYS_BAD_RECORD.CREATE_USER_NAME, SYS_BAD_RECORD.CREATE_USER_ID,SYS_BAD_RECORD.SHIFT,SYS_BAD_RECORD.WORK_SHOP,SYS_BAD_RECORD.WORK_SHOP_NAME,sum(SYS_BAD_RECORD.NUM).as("num"));
                queryWrapper.groupBy(SYS_BAD_RECORD.WORK_PLAN_ID);
                queryWrapper.orderBy(SYS_BAD_RECORD.WORK_PLAN_ID, true);
                List<SysBadRecord> recordList = this.sysBadRecordService.list(queryWrapper);
                for (SysBadRecord record1 : recordList) {
                    queryWrapper = QueryWrapper.create();
                    queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
                    queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP.eq(badRecord.getWorkShop()));
                    queryWrapper.where(SYS_BAD_RECORD.WORK_PLAN_ID.eq(record1.getWorkPlanId()));
                    queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(productDate));
                    queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
                    queryWrapper.select(SYS_BAD_RECORD.REASON_TYPE, SYS_BAD_RECORD.ID, SYS_BAD_RECORD.REASON_NAME, sum(SYS_BAD_RECORD.NUM).as("num"), SYS_BAD_RECORD.WORK_PLAN_ID, SYS_BAD_RECORD.PRODUCT_NAME, SYS_BAD_RECORD.SHORT_NAME,SYS_BAD_RECORD.MACHINE_NAME);
                    queryWrapper.groupBy(SYS_BAD_RECORD.REASON_NAME);
                    queryWrapper.orderBy(SYS_BAD_RECORD.NUM, false);
                    List<SysBadRecord> recordList1 = this.sysBadRecordService.list(queryWrapper);
                    record1.setBadRecordList(recordList1);
                }
                record.setBadRecordList(recordList);
            }
            badRecord.setBadRecordList(badRecordList);

        }
        return sysBadRecordList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysBadRecordList);
    }

    @PostMapping("/listByConditionSummary")
    public Result<?> listByConditionSummary(@RequestBody SysBadRecord sysBadRecord) {
        log.error("SysBadRecord:{}", sysBadRecord);
        String productDate = fromDateToString("yyyy-MM-dd", sysBadRecord.getProductDate());
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
        queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(productDate));
        queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
        queryWrapper.select(distinct(SYS_BAD_RECORD.WORK_SHOP));
        queryWrapper.orderBy(SYS_BAD_RECORD.WORK_SHOP, true);
        System.out.println("SQL:" + queryWrapper.toSQL());
        List<SysBadRecord> sysBadRecordList = this.sysBadRecordService.list(queryWrapper);
        for (SysBadRecord badRecord : sysBadRecordList) {
            queryWrapper=QueryWrapper.create();
            queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP.eq(badRecord.getWorkShop()));
            queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(productDate));
            queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
            queryWrapper.select(SYS_BAD_RECORD.MACHINE_NAME,sum(SYS_BAD_RECORD.NUM).as("num"), SYS_BAD_RECORD.WORK_PLAN_ID, SYS_BAD_RECORD.PRODUCT_NAME, SYS_BAD_RECORD.SHORT_NAME);
            queryWrapper.groupBy(SYS_BAD_RECORD.MACHINE_NAME);
            queryWrapper.orderBy(SYS_BAD_RECORD.MACHINE_NAME,true);
            List<SysBadRecord> badRecordList=this.sysBadRecordService.list(queryWrapper);
            badRecord.setBadRecordList(badRecordList);
        }
        return sysBadRecordList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysBadRecordList);
    }

    @PostMapping("/updateBatch")
    public Result<?> updateBatch(@RequestBody List<SysBadRecord> sysBadRecordList) {
//        boolean result = this.sysBadRecordService.updateBatch(sysBadRecordList);
        boolean result=false;
        List<SysBadRecord1> sysBadRecord1List=new ArrayList<>();
        for(SysBadRecord sysBadRecord:sysBadRecordList){
            SysBadRecord badRecord=this.sysBadRecordService.getById(sysBadRecord.getId());
            if(badRecord!=null){
                if(sysBadRecord.getNum()<=0){
                   result= this.sysBadRecordService.removeById(sysBadRecord.getId());
                }else{
                    badRecord.setNum(sysBadRecord.getNum());
                    result=this.sysBadRecordService.updateById(sysBadRecord);


                }
                if(badRecord.getBadRecord1Id()!=null){
                    SysBadRecord1 sysBadRecord1=new SysBadRecord1();
                    sysBadRecord1.setId(Integer.valueOf(badRecord.getBadRecord1Id()));
                    sysBadRecord1.setNum(sysBadRecord1.getNum());
                    sysBadRecord1List.add(sysBadRecord1);
                }


            }else{
                return ResultTool.fail();
            }
        }
        this.sysBadRecord1Service.updateBatch(sysBadRecord1List);
        return result ? ResultTool.success() : ResultTool.fail();
    }

    @PostMapping("/getByWorkPlanId")
    public Result<?> getBadRecordDataListByWorkPlanId(@RequestBody SysBadRecord sysBadRecord) {
        log.error("BadRecord:{}", sysBadRecord);
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
        queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP.eq(sysBadRecord.getWorkShop()));
        queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
        queryWrapper.where(SYS_BAD_RECORD.WORK_PLAN_ID.eq(sysBadRecord.getWorkPlanId()));
        queryWrapper.where(SYS_BAD_RECORD.MACHINE_NAME.eq(sysBadRecord.getMachineName()));
        queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",sysBadRecord.getProductDate())));
        queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
        queryWrapper.select(distinct(SYS_BAD_RECORD.REASON_TYPE));
        List<SysBadRecord> sysBadRecordList = this.sysBadRecordService.list(queryWrapper);
        for (SysBadRecord badRecord : sysBadRecordList) {
            AtomicInteger num = new AtomicInteger();
            queryWrapper = QueryWrapper.create();
            queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
            queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP.eq(sysBadRecord.getWorkShop()));
            queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
            queryWrapper.where(SYS_BAD_RECORD.WORK_PLAN_ID.eq(sysBadRecord.getWorkPlanId()));
            queryWrapper.where(SYS_BAD_RECORD.MACHINE_NAME.eq(sysBadRecord.getMachineName()));
            queryWrapper.where(SYS_BAD_RECORD.REASON_TYPE.eq(badRecord.getReasonType()));
            queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",sysBadRecord.getProductDate())));
            queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
            List<SysBadRecord> badRecordList = this.sysBadRecordService.list(queryWrapper);
            badRecordList.forEach(item -> {
                num.addAndGet(item.getNum());
            });
            badRecord.setNum(num.get());
            badRecord.setBadRecordList(badRecordList);
        }
        return sysBadRecordList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysBadRecordList);
    }
    @PostMapping("/getBadRecordDataByWorkPlanId")
    public Result<?> getBadRecordDataByWorkPlanId(@RequestBody SysBadRecord sysBadRecord){
        log.error("BadRecord:{}",sysBadRecord);
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP.eq(sysBadRecord.getWorkShop()));
        queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
        queryWrapper.where(SYS_BAD_RECORD.WORK_PLAN_ID.eq(sysBadRecord.getWorkPlanId()));
        queryWrapper.where(SYS_BAD_RECORD.MACHINE_NAME.eq(sysBadRecord.getMachineName()));
        queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",sysBadRecord.getProductDate())));
        queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
        queryWrapper.select(distinct(SYS_BAD_RECORD.WORK_PLAN_ID), SYS_BAD_RECORD.PRODUCT_ID, SYS_BAD_RECORD.PRODUCT_NAME, SYS_BAD_RECORD.SHORT_NAME, SYS_BAD_RECORD.CREATE_USER_NAME, SYS_BAD_RECORD.CREATE_USER_ID,SYS_BAD_RECORD.SHIFT,SYS_BAD_RECORD.WORK_SHOP,SYS_BAD_RECORD.WORK_SHOP_NAME,sum(SYS_BAD_RECORD.NUM).as("num"));
        SysBadRecord badRecord=this.sysBadRecordService.getOne(queryWrapper);
        return  badRecord==null?ResultTool.fail():ResultTool.success(badRecord);
    }

    @PostMapping("/getDataForPrint/{pageNum}/{size}")
    public  Result<?> getDataForPrint(@RequestBody SysBadRecord sysBadRecord, @PathVariable long pageNum, @PathVariable long size){
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
        queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",sysBadRecord.getProductDate())));
        queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
        if(sysBadRecord.getProductId()!=null){
            queryWrapper.where(SYS_BAD_RECORD.PRODUCT_ID.like(sysBadRecord.getProductId()));
        }
        queryWrapper.select(distinct(SYS_BAD_RECORD.MACHINE_NAME),SYS_BAD_RECORD.SHIFT,SYS_BAD_RECORD.PRODUCT_ID);
        queryWrapper.orderBy(SYS_BAD_RECORD.MACHINE_NAME,true);
//        List<SysBadRecord> sysBadRecordList=this.sysBadRecordService.list(queryWrapper);
        Page<SysBadRecord> badRecordPage=new Page<>();
        badRecordPage.setPageNumber(pageNum);
        badRecordPage.setPageSize(size);
        Page<SysBadRecord> recordPage=this.sysBadRecordService.page(badRecordPage,queryWrapper);
        for(SysBadRecord badRecord:recordPage.getRecords()){
            queryWrapper=QueryWrapper.create();
            queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
            queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",sysBadRecord.getProductDate())));
            queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
            queryWrapper.where(SYS_BAD_RECORD.MACHINE_NAME.eq(badRecord.getMachineName()));
            if(sysBadRecord.getProductId()!=null){
                queryWrapper.where(SYS_BAD_RECORD.PRODUCT_ID.like(sysBadRecord.getProductId()));
            }
            queryWrapper.select(sum(SYS_BAD_RECORD.NUM).as("num"),SYS_BAD_RECORD.REASON_NAME,SYS_BAD_RECORD.MACHINE_NAME);
            queryWrapper.groupBy(SYS_BAD_RECORD.REASON_NAME);

            List<SysBadRecord> badRecordList=this.sysBadRecordService.list(queryWrapper);
            int totalNum=badRecordList.stream().mapToInt(SysBadRecord::getNum).sum();
            badRecord.setTotalNum(totalNum);
            log.error("SQL:{}",queryWrapper.toSQL());
            badRecord.setBadRecordList(badRecordList);

            queryWrapper=QueryWrapper.create();
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq(sysBadRecord.getShift()));
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME.eq(badRecord.getMachineName()));
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",sysBadRecord.getProductDate())));
            queryWrapper.limit(1);
            SysProductRecordShift productRecordShift=this.sysProductRecordShiftService.getMapper().selectOneWithRelationsByQuery(queryWrapper);
            log.error("SQL:{}",queryWrapper.toSQL());
            badRecord.setProductRecordShift(productRecordShift);
        }
        BadRecordModel badRecordModel=new BadRecordModel();
        queryWrapper=QueryWrapper.create();
        queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
        queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",sysBadRecord.getProductDate())));
        queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
        if(sysBadRecord.getProductId()!=null){
            queryWrapper.where(SYS_BAD_RECORD.PRODUCT_ID.like(sysBadRecord.getProductId()));
        }
        queryWrapper.select(distinct(SYS_BAD_RECORD.REASON_NAME));
        queryWrapper.orderBy(SYS_BAD_RECORD.REASON_ID,true);
//        queryWrapper.orderBy(SYS_BAD_RECORD.REASON_ID,true);
        List<SysBadRecord> badReasonList=this.sysBadRecordService.list(queryWrapper);
        badRecordModel.setBadRecordPage(badRecordPage);
        badRecordModel.setBadReasonList(badReasonList);

        return badRecordPage.getRecords().isEmpty()?ResultTool.fail():ResultTool.success(badRecordModel);


    }
   @PostMapping("/getDataForPrint1/{pageNum}/{size}")
    public  Result<?> getDataForPrint1(@RequestBody SysBadRecord sysBadRecord, @PathVariable long pageNum, @PathVariable long size){
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
        queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",sysBadRecord.getProductDate())));
        queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
        if(sysBadRecord.getProductId()!=null){
            queryWrapper.where(SYS_BAD_RECORD.PRODUCT_ID.like(sysBadRecord.getProductId()));
        }
        queryWrapper.select(distinct(SYS_BAD_RECORD.MACHINE_NAME),SYS_BAD_RECORD.SHIFT,SYS_BAD_RECORD.PRODUCT_ID);
        queryWrapper.orderBy(SYS_BAD_RECORD.MACHINE_NAME,true);
//        List<SysBadRecord> sysBadRecordList=this.sysBadRecordService.list(queryWrapper);
        Page<SysBadRecord> badRecordPage=new Page<>();
        badRecordPage.setPageNumber(pageNum);
        badRecordPage.setPageSize(size);
        Page<SysBadRecord> recordPage=this.sysBadRecordService.page(badRecordPage,queryWrapper);
        for(SysBadRecord badRecord:recordPage.getRecords()){
            queryWrapper=QueryWrapper.create();
            queryWrapper.where(SYS_BAD_RECORD.WORK_SHOP_NAME.eq(sysBadRecord.getWorkShopName()));
            queryWrapper.where(SYS_BAD_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",sysBadRecord.getProductDate())));
            queryWrapper.where(SYS_BAD_RECORD.SHIFT.eq(sysBadRecord.getShift()));
            queryWrapper.where(SYS_BAD_RECORD.MACHINE_NAME.eq(badRecord.getMachineName()));
            if(sysBadRecord.getProductId()!=null){
                queryWrapper.where(SYS_BAD_RECORD.PRODUCT_ID.like(sysBadRecord.getProductId()));
            }
            queryWrapper.select(sum(SYS_BAD_RECORD.NUM).as("num"),SYS_BAD_RECORD.REASON_NAME,SYS_BAD_RECORD.MACHINE_NAME,SYS_BAD_RECORD.REASON_ID);
            queryWrapper.groupBy(SYS_BAD_RECORD.REASON_NAME);

            List<SysBadRecord> badRecordList=this.sysBadRecordService.list(queryWrapper);
            int totalNum=badRecordList.stream().mapToInt(SysBadRecord::getNum).sum();
            badRecord.setTotalNum(totalNum);
            log.error("SQL:{}",queryWrapper.toSQL());
            badRecord.setBadRecordList(badRecordList);

            queryWrapper=QueryWrapper.create();
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.SHIFT.eq(sysBadRecord.getShift()));
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.MACHINE_NAME.eq(badRecord.getMachineName()));
            queryWrapper.where(SYS_PRODUCT_RECORD_SHIFT.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd",sysBadRecord.getProductDate())));
            queryWrapper.limit(1);
            SysProductRecordShift productRecordShift=this.sysProductRecordShiftService.getMapper().selectOneWithRelationsByQuery(queryWrapper);
            log.error("SQL:{}",queryWrapper.toSQL());
            badRecord.setProductRecordShift(productRecordShift);
        }




        return badRecordPage.getRecords().isEmpty()?ResultTool.fail():ResultTool.success(badRecordPage);


    }

}
